<template>
  <div class="distribution-settlement">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>佣金结算</span>
          <div>
            <el-button type="primary" @click="handleBatchSettle" :disabled="selectedRows.length === 0">批量结算</el-button>
            <el-button @click="handleAutoSettle">自动结算</el-button>
          </div>
        </div>
      </template>

      <!-- 结算统计 -->
      <el-row :gutter="20" style="margin-bottom: 20px;">
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-value">¥{{ settlementStats.total_commission }}</div>
              <div class="stat-label">总佣金</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-value">¥{{ settlementStats.settled_commission }}</div>
              <div class="stat-label">已结算佣金</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-value">¥{{ settlementStats.unsettled_commission }}</div>
              <div class="stat-label">未结算佣金</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-value">¥{{ settlementStats.today_settled }}</div>
              <div class="stat-label">今日结算</div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 搜索条件 -->
      <el-form :inline="true" class="search-form">
        <el-form-item label="分销员姓名">
          <el-input
            v-model="searchForm.customer_name"
            placeholder="请输入分销员姓名"
            clearable
            @clear="handleSearch"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="全部" value="" />
            <el-option label="待结算" value="0" />
            <el-option label="已结算" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="searchForm.date_range"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 佣金结算列表 -->
      <el-table
        :data="tableData"
        border
        stripe
        v-loading="loading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column label="分销员" min-width="150">
          <template #default="scope">
            <div>{{ scope.row.customer_name }}</div>
          </template>
        </el-table-column>
        <el-table-column label="来源用户" min-width="150">
          <template #default="scope">
            <div>{{ scope.row.from_customer_name || '直接购买' }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="order_no" label="订单号" width="180" />
        <el-table-column label="订单金额" width="120">
          <template #default="scope">
            ¥{{ scope.row.order_amount }}
          </template>
        </el-table-column>
        <el-table-column label="佣金金额" width="120">
          <template #default="scope">
            ¥{{ scope.row.commission_amount }}
          </template>
        </el-table-column>
        <el-table-column prop="level" label="分销层级" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.level === 1">一级</el-tag>
            <el-tag v-else type="success">二级</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.status === 0">待结算</el-tag>
            <el-tag v-else type="success">已结算</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="create_time" label="创建时间" width="180" />
        <el-table-column label="结算时间" width="180">
          <template #default="scope">
            {{ scope.row.settle_time || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="scope">
            <el-button
              v-if="scope.row.status === 0"
              size="small"
              type="primary"
              @click="handleSettle(scope.row)"
            >
              结算
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        @current-change="handlePageChange"
        :current-page="currentPage"
        :page-size="pageSize"
        layout="total, prev, pager, next"
        :total="total"
        style="margin-top: 20px; text-align: right;"
      />
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'

const VITE_URL = (window as any).VITE_URL

// 表格数据
const tableData = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(15)
const total = ref(0)

// 结算统计
const settlementStats = ref({
  total_commission: 0,
  settled_commission: 0,
  unsettled_commission: 0,
  today_settled: 0,
  this_month_settled: 0
})

// 搜索表单
const searchForm = ref({
  customer_name: '',
  status: '',
  date_range: []
})

// 选中的行
const selectedRows = ref([])

// 获取佣金结算列表
const getCommissionList = async () => {
  loading.value = true
  try {
    const params = new URLSearchParams()
    params.append('page', currentPage.value.toString())
    params.append('limit', pageSize.value.toString())
    
    if (searchForm.value.customer_name) {
      params.append('customer_name', searchForm.value.customer_name)
    }
    if (searchForm.value.status !== '') {
      params.append('status', searchForm.value.status)
    }
    if (searchForm.value.date_range && searchForm.value.date_range.length === 2) {
      params.append('start_time', searchForm.value.date_range[0])
      params.append('end_time', searchForm.value.date_range[1])
    }
    
    const url = `${VITE_URL}/admin.distribution_settlement/commission_list?${params.toString()}`
    const res = await axios.get(url)
    if (res.data.status === 0) {
      tableData.value = res.data.data.list
      total.value = res.data.data.total
    }
  } catch (error) {
    ElMessage.error('获取佣金结算列表失败')
  } finally {
    loading.value = false
  }
}

// 获取结算统计
const getSettlementStats = async () => {
  try {
    const url = `${VITE_URL}/admin.distribution_settlement/settlement_stats`
    const res = await axios.get(url)
    if (res.data.status === 0) {
      settlementStats.value = res.data.data
    }
  } catch (error) {
    ElMessage.error('获取结算统计失败')
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  getCommissionList()
}

// 重置
const handleReset = () => {
  searchForm.value = {
    customer_name: '',
    status: '',
    date_range: []
  }
  currentPage.value = 1
  getCommissionList()
}

// 分页变化
const handlePageChange = (page: number) => {
  currentPage.value = page
  getCommissionList()
}

// 选中行变化
const handleSelectionChange = (rows: any[]) => {
  selectedRows.value = rows
}

// 结算单个佣金
const handleSettle = (row: any) => {
  ElMessageBox.confirm(
    `确定要结算该笔佣金吗？`,
    '确认结算',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const url = `${VITE_URL}/admin.distribution_settlement/batch_settle`
      const res = await axios.post(url, { ids: [row.id] })
      if (res.data.status === 0) {
        ElMessage.success('结算成功')
        getCommissionList()
        getSettlementStats()
      } else {
        ElMessage.error(res.data.message || '结算失败')
      }
    } catch (error) {
      ElMessage.error('结算失败')
    }
  }).catch(() => {
    // 取消结算
  })
}

// 批量结算
const handleBatchSettle = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要结算的佣金记录')
    return
  }
  
  ElMessageBox.confirm(
    `确定要结算选中的${selectedRows.value.length}笔佣金吗？`,
    '确认结算',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const ids = selectedRows.value.map((row: any) => row.id)
      const url = `${VITE_URL}/admin.distribution_settlement/batch_settle`
      const res = await axios.post(url, { ids })
      if (res.data.status === 0) {
        ElMessage.success('结算成功')
        getCommissionList()
        getSettlementStats()
      } else {
        ElMessage.error(res.data.message || '结算失败')
      }
    } catch (error) {
      ElMessage.error('结算失败')
    }
  }).catch(() => {
    // 取消结算
  })
}

// 自动结算
const handleAutoSettle = () => {
  ElMessageBox.confirm(
    `确定要执行自动结算吗？系统将根据规则自动结算符合条件的佣金。`,
    '确认自动结算',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const url = `${VITE_URL}/admin.distribution_settlement/auto_settle`
      const res = await axios.post(url)
      if (res.data.status === 0) {
        ElMessage.success('自动结算执行成功')
        getCommissionList()
        getSettlementStats()
      } else {
        ElMessage.error(res.data.message || '自动结算执行失败')
      }
    } catch (error) {
      ElMessage.error('自动结算执行失败')
    }
  }).catch(() => {
    // 取消自动结算
  })
}

// 初始化数据
getCommissionList()
getSettlementStats()
</script>

<style scoped>
.distribution-settlement {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.stat-card {
  text-align: center;
}

.stat-content {
  padding: 20px 0;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #667eea;
  margin-bottom: 5px;
}

.stat-label {
  color: #999;
}
</style>